import collisions from "./collisions.js"
import pcControls from "./pcControl.js";

/*----------------- 更新用户信息--------------------*/
export default function updatePlayer(delta) {
  console.log('data.state',walking)
  const deltaTime = Math.min( 0.05, delta) / STEPS_PER_FRAME;
  const playerCamera = scene.getObjectByName("playerCamera");
  if(playerCamera){
    roleMove()
    cameraMove(playerCamera)
    roleRotation(playerCamera)
    socketUpdate()
  }
  // 多次检测防止物体速度过快导致穿模
  for ( let i = 0; i < STEPS_PER_FRAME; i ++ ) {
      collisions(deltaTime)
  }
  pcControls(delta,playerCamera)
}
// 人物移动
function roleMove() {
  if (distance > 0) {
      distance -= speed;
      // 沿目标方向移动
      player.translateOnAxis(targetNorm, speed);
      player.rotation.z = 0;
  }
  // 到达后
  if (distance == 0 || distance < 0) {
      action.walking.stop();
      action.idle.play();
      walking=false
      let point=scene.getObjectByName('point')
      scene.remove(point)
  }
}
// 相机追随
function cameraMove(playerCamera){
  let positonCopy = playerCamera.getWorldPosition(new THREE.Vector3());
  transform(positonCopy)
  camera.lookAt(positonCopy);
  control.target.copy(positonCopy)
  camera.updateMatrix();
}
// 球坐标转化为直角坐标系
function transform(pos){
	let spherical =control.getSpherical()
  let position = new THREE.Vector3()
  position.setFromSpherical(spherical)
  camera.position.set(pos.x+position.x,pos.y+position.y,pos.z+position.z)
}
// 人物旋转
function roleRotation(playerCamera) {
  let actor = scene.getObjectByName("actor");
  //旋转
  if (distance > 0.05) {
    // 人物看向目标
    playerCamera.lookAt(target.x, player.position.y, target.z);
    let cameraClone = playerCamera.quaternion.clone();
    actor.quaternion.slerp(cameraClone, 0.1);
  }
}
// socket更新用户信息
function socketUpdate(){
  let playerCamera = scene.getObjectByName("playerCamera");
  if(playerCamera){
    let obj = {
      playerPosition: player.position,
      playerQuaternion: playerCamera.quaternion,
      state: walking,
      id: player.name
    };
    socket.emit("message", obj);
  }
}